package com.yachang.qym.usbhost.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.baidu.navisdk.adapter.base.BaiduNaviSDKProxy;
import com.baidu.vi.VDeviceAPI;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import com.yachang.qym.usbhost.R;
import com.yachang.qym.usbhost.UsbApplication;
import com.yachang.qym.usbhost.adapter.MyFragmentAdapter;
import com.yachang.qym.usbhost.fragment.ContactsFragment;
import com.yachang.qym.usbhost.fragment.HighFragment;
import com.yachang.qym.usbhost.fragment.HomeFragment;
import com.yachang.qym.usbhost.fragment.MyFragment;
import com.yachang.qym.usbhost.fragment.OutPoliceFragment;
import com.yachang.qym.usbhost.fragment.RouteFragment;
import com.yachang.qym.usbhost.model.VersionModel;
import com.yachang.qym.usbhost.service.CheckNetService;
import com.yachang.qym.usbhost.service.GetDataService;
import com.yachang.qym.usbhost.service.LocationService;
import com.yachang.qym.usbhost.service.ScreenOnService;
import com.yachang.qym.usbhost.usbserial.driver.UsbSerialDriver;
import com.yachang.qym.usbhost.usbserial.driver.UsbSerialPort;
import com.yachang.qym.usbhost.usbserial.driver.UsbSerialProber;
import com.yachang.qym.usbhost.utils.API;
import com.yachang.qym.usbhost.utils.AllData;
import com.yachang.qym.usbhost.utils.GetDataFormUSB;
import com.yachang.qym.usbhost.utils.NotificationCenter;
import com.yachang.qym.usbhost.utils.SendData;
import com.yachang.qym.usbhost.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import static com.baidu.navisdk.adapter.PackageUtil.getSdcardDir;
import static com.yachang.qym.usbhost.utils.API.isNetRunning;
import static com.yachang.qym.usbhost.utils.API.mSocket;

@SuppressLint("HandlerLeak")
public class MainActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private TabLayout tabLayout;

    public static UsbManager mUsbManager;
    public static UsbSerialPort sPort = null;

    private GetDataFormUSB formUSB;
    private ProgressDialog dialog;
    private int mPopupWeight;
    private int chooseTab = 0;
    private boolean isNetRunning = true;

    //导航相关  测试提交
    private static final String APP_FOLDER_NAME = "BNSDKSimpleDemo";

    private String mSDCardPath = null;

    private Emitter.Listener onNewMessage = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(!AllData.isInPolice) {
                        Log.i("SocketData", args[0].toString());
                        JSONObject response = (JSONObject) args[0];
                        try {
                            if (response.getInt("code") == 1) {
                                if (!response.getJSONObject("result").equals(null)) {
                                    ToastUtil.showToast("已进入出警模式！");
                                    AllData.outPolice_id = response.getJSONObject("result").getString("_id");

                                    viewPager = (ViewPager) findViewById(R.id.viewpager);
                                    if (viewPager != null) {
                                        setupViewPager(viewPager);
                                    }
                                    viewPager.setOffscreenPageLimit(7);
                                    tabLayout = (TabLayout) findViewById(R.id.tabs);
                                    tabLayout.setupWithViewPager(viewPager);
                                    tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
                                    tabLayout.setSelectedTabIndicatorColor(getResources().getColor(android.R.color.holo_red_light));

                                    AllData.locationIntent = new Intent(MainActivity.this, LocationService.class); //启动位置更新服务
                                    startService(AllData.locationIntent);

                                    AllData.usbIntent = new Intent(MainActivity.this, GetDataService.class); //启动对讲机数据更新服务
                                    startService(AllData.usbIntent);

                                    Intent intent = new Intent(MainActivity.this, ScreenOnService.class); //启动屏幕开屏检测
                                    startService(intent);

                                    dialog.dismiss();
                                    AllData.isInPolice = true;

                                    if (initDirs()) {
                                        initNavi();
                                    }

                                }
                            } else if (response.getInt("code") == 2) {
                                showUnRegisterDialog();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    };



    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    private void initNavi() {

        BNOuterTTSPlayerCallback ttsCallback = null;

        BaiduNaviManager.getInstance().init(MainActivity.this, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
            @Override
            public void onAuthResult(int status, String msg) {
                Toast.makeText(MainActivity.this, "导航引擎初始化成功", Toast.LENGTH_SHORT).show();
            }

            public void initSuccess() {
                initSetting();
            }

            public void initStart() {
            }

            public void initFailed() {
                Toast.makeText(MainActivity.this, "导航引擎初始化失败", Toast.LENGTH_SHORT).show();
            }


        },  null, ttsHandler, ttsPlayStateListener);

    }

    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    break;
                }
                default :
                    break;
            }
        }
    };

    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

        @Override
        public void playEnd() {

        }

        @Override
        public void playStart() {

        }
    };

    private void initSetting(){
        // 设置是否双屏显示
        BNaviSettingManager.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        // 设置导航播报模式
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // 是否开启路况
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            finish();
        }

        ;
    };

    @Override
    protected void onDestroy() {
        dialog.dismiss();
        if (BaiduNaviSDKProxy.isNaviInited())
            BaiduNaviSDKProxy.uninit();
        VDeviceAPI.unsetNetworkChangedCallback();

        if (sPort != null) {
            try {
                sPort.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
        //android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        stopService(getIntent());
        isNetRunning = getIntent().getBooleanExtra("isNetRunning", true);
        AllData.isNetLogin = isNetRunning;
        dialog = new ProgressDialog(this);
        dialog.setCancelable(false);
        NotificationCenter.getInstance().addObserver("isNewData", this, "isNewData");
        NotificationCenter.getInstance().addObserver("contactFinish", this, "contactFinish");
        NotificationCenter.getInstance().addObserver("calledFinish", this, "calledFinish");
        NotificationCenter.getInstance().addObserver("routeFinish", this, "routeFinish");
        NotificationCenter.getInstance().addObserver("areaFinish", this, "areaFinish");
        NotificationCenter.getInstance().addObserver("nowRouteFinish", this, "nowRouteFinish");
        NotificationCenter.getInstance().addObserver("machineInfoFinish", this, "machineInfoFinish");
        NotificationCenter.getInstance().addObserver("HelpInfoFinish", this, "HelpInfoFinish");
        NotificationCenter.getInstance().addObserver("machineIdFinish", this, "machineIdFinish");
        NotificationCenter.getInstance().addObserver("ReopenApp", this, "ReopenApp");
        if(isNetRunning){
            mSocket.on("inPolice", onNewMessage);
            enterOutPolice(true);
        } else {
            viewPager = (ViewPager) findViewById(R.id.viewpager);
            if (viewPager != null) {
                setupViewPager(viewPager);
            }
            viewPager.setOffscreenPageLimit(7);
            tabLayout = (TabLayout) findViewById(R.id.tabs);
            tabLayout.setupWithViewPager(viewPager);
            tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
            tabLayout.setSelectedTabIndicatorColor(getResources().getColor(android.R.color.holo_red_light));
            AllData.usbIntent = new Intent(MainActivity.this, GetDataService.class); //启动对讲机数据更新服务
            startService(AllData.usbIntent);
            Intent intent = new Intent(MainActivity.this, CheckNetService.class);
            startService(intent);
            dialog.dismiss();
            AllData.isInPolice = true;
        }
//        connectUsb();
    }

    public void ReopenApp(){
        final android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(getApplicationContext());
        alertDialog.setTitle("提示");
        alertDialog.setMessage("网络已可用，请重新登录！");
        alertDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        AllData.isLogin = false;
                        AllData.isInPolice = false;
                        MainActivity.this.stopService(AllData.usbIntent);
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        startActivity(intent);
                        MainActivity.this.finish();
                    }
                });

        alertDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(MainActivity.this, CheckNetService.class);
                        startService(intent);
                        dialog.dismiss();
                    }
                });

        Dialog ad = alertDialog.create();

        ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        ad.setCanceledOnTouchOutside(true);//点击外面区域不会让dialog消失
        ad.show();
    }

    private void setupViewPager(ViewPager viewPager) {
        MyFragmentAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager());
        adapter.addFragment(new HomeFragment(), "主页");
        adapter.addFragment(new HighFragment(), "搜救");
        adapter.addFragment(new OutPoliceFragment(), "出警");
        adapter.addFragment(new ContactsFragment(), "联系人");
        adapter.addFragment(new RouteFragment(), "信道");
        adapter.addFragment(new MyFragment(), "我的");
        viewPager.setAdapter(adapter);
    }


    private void connectUsb() {
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        final List<UsbSerialDriver> drivers = UsbSerialProber.getDefaultProber().findAllDrivers(mUsbManager);
        if (!drivers.isEmpty()) {
            UsbSerialDriver driver = drivers.get(0);
            UsbDeviceConnection connection = mUsbManager.openDevice(driver.getDevice());
            sPort = driver.getPorts().get(0);

            if (connection == null) {
                Toast.makeText(this, "设备连接异常！", Toast.LENGTH_SHORT).show();
                MainActivity.this.finish();
                return;
            } else {
                try {
                    if (sPort != null) {
                        sPort.open(connection);
                        sPort.setParameters(38400, 8, UsbSerialPort.STOPBITS_2, UsbSerialPort.PARITY_NONE);
                        Toast.makeText(this, "设备连接正常！", Toast.LENGTH_SHORT).show();
                        dialog.setTitle("数据更新");
                        dialog.show();
                        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                            @Override
                            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                                if (keyCode == KeyEvent.KEYCODE_BACK) {
                                    Intent intent = new Intent(Intent.ACTION_MAIN);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intent.addCategory(Intent.CATEGORY_HOME);
                                    startActivity(intent);
                                    return true;
                                }
                                return false;
                            }
                        });
                        formUSB = new GetDataFormUSB(sPort, MainActivity.this);
                        dialog.setMessage("正在获取当前信道信息，请稍后");
                        formUSB.sendNowRoute();
                    } else {
                        Toast.makeText(this, "未找到设备，请检查连接", Toast.LENGTH_SHORT).show();
                        MainActivity.this.finish();
                    }
                } catch (IOException e) {
                    try {
                        sPort.close();
                    } catch (IOException e2) {

                    }
                    sPort = null;
                    return;
                }
            }
        } else {
            Toast.makeText(this, "未找到设备，请检查连接", Toast.LENGTH_SHORT).show();
            MainActivity.this.finish();
        }
    }

    public void nowRouteFinish() {
        dialog.setMessage("正在检测数据更新，请稍后...");
        formUSB.sendTestNewData();
    }

    public void isNewData() {
        dialog.setMessage("正在获取本机编号...");
        formUSB.sendMachineId();
    }

    public void machineIdFinish() {
        dialog.setMessage("正在获取联系人数据，请稍候...");
        formUSB.sendContactData();
    }

    public void contactFinish() {
        dialog.setMessage("正在获取接收组列表信息，请稍后");
        formUSB.sendCalledData();
    }

    public void calledFinish() {
        dialog.setMessage("正在获取信道列表信息，请稍后");
        formUSB.sendRouteData();
    }

    public void routeFinish() {
        dialog.setMessage("正在获取区域列表信息，请稍后");
        formUSB.sendAreaData();
    }

    public void areaFinish() {
        dialog.setMessage("正在获取对讲机配置信息，请稍后");
        formUSB.sendMachineInfo();
    }

    public void machineInfoFinish() {
        dialog.setMessage("正在获取本机高度等信息，请稍后");
        formUSB.sendHighInfo();
    }

    public void HelpInfoFinish() {
        dialog.setMessage("正在登录，请稍后");

        if(isNetRunning){
            mSocket.on("inPolice", onNewMessage);
            enterOutPolice(true);
        } else {
            viewPager = (ViewPager) findViewById(R.id.viewpager);
            if (viewPager != null) {
                setupViewPager(viewPager);
            }
            viewPager.setOffscreenPageLimit(7);
            tabLayout = (TabLayout) findViewById(R.id.tabs);
            tabLayout.setupWithViewPager(viewPager);
            tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
            tabLayout.setSelectedTabIndicatorColor(getResources().getColor(android.R.color.holo_red_light));
            AllData.usbIntent = new Intent(MainActivity.this, GetDataService.class); //启动对讲机数据更新服务
            startService(AllData.usbIntent);
            Intent intent = new Intent(MainActivity.this, CheckNetService.class);
            startService(intent);
            dialog.dismiss();
            AllData.isInPolice = true;
        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
        super.onBackPressed();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            showVoiceDialog(true);
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            showVoiceDialog(false);
            return true;
        }
        return true;
    }

    @Override
    protected void onPause() {
        chooseTab = tabLayout.getSelectedTabPosition();
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(AllData.isInPolice)
            tabLayout.getTabAt(chooseTab).select();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        switch (intent.getIntExtra("index", 0)){
            case 0:
                tabLayout.getTabAt(0).select();
                break;
            case 1:
                tabLayout.getTabAt(1).select();
                break;
            case 2:
                tabLayout.getTabAt(2).select();
                break;
            case 3:
                tabLayout.getTabAt(3).select();
                break;
            case 4:
                tabLayout.getTabAt(4).select();
                break;
            case 5:
                tabLayout.getTabAt(5).select();
                break;
        }
    }

    private void enterOutPolice(boolean isFirst){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("mid", AllData.machineId);
        map.put("uid", AllData.userModel.get_id());
        map.put("userImage", AllData.userModel.getImageUrl());
        map.put("username", AllData.userModel.getUsername());
        map.put("fid", AllData.userModel.getFirecompany_id());
        map.put("isFirst", isFirst);
        JSONObject jsonObject = new JSONObject(map);

        mSocket.emit("inPolice", jsonObject);
    }

    private void showUnRegisterDialog(){
        new AlertDialog.Builder(MainActivity.this).setTitle("提醒").setIcon(R.drawable.icon).setMessage("确定注销上次登录?取消将退出程序。")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        enterOutPolice(false);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        }).setCancelable(false).show();
    }

    boolean isFirst = true;

    private void showVoiceDialog(final boolean isUp) {
        isFirst = true;
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View contentView = inflaterDl.inflate(R.layout.popup_voice, null);

        final TextView tvCount = (TextView) contentView.findViewById(R.id.tv_voice_num);

        final View viewParent = contentView.findViewById(R.id.view_parent);
        final View viewCount = contentView.findViewById(R.id.view_count);
        ViewTreeObserver vto = viewParent.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                mPopupWeight = viewParent.getMeasuredWidth();
                if (isFirst) {
                    setDialog(tvCount, viewCount, isUp);
                    isFirst = false;
                }
                return true;
            }
        });

        //对话框
        final Dialog dialog = new AlertDialog(this) {
            @Override
            public boolean onKeyDown(int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
                    setDialog(tvCount, viewCount, true);
                    return true;
                }
                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
                    setDialog(tvCount, viewCount, false);
                    return true;
                }

                return super.onKeyDown(keyCode, event);
            }
        };
        dialog.show();
        dialog.setContentView(contentView);
    }

    private void setDialog(TextView tvCount, View viewCount, boolean isUp) {
        RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) viewCount.getLayoutParams();
        if (isUp) {
            if (AllData.voice < 100) {
                AllData.voice = AllData.voice + 5;
                if (AllData.voice >= 100) {
                    AllData.voice = 100;
                    linearParams.width = mPopupWeight;
                } else {
                    linearParams.width = mPopupWeight * AllData.voice / 100;
                }
            } else {
                AllData.voice = 100;
                linearParams.width = mPopupWeight;
            }
            tvCount.setText(AllData.voice + "");
            SendData.data = SendData.sendVoice(AllData.voice);
            SendData.needSend = true;
        } else {
            if (AllData.voice > 0) {
                AllData.voice = AllData.voice - 5;
                if (AllData.voice <= 0) {
                    AllData.voice = 0;
                    linearParams.width = 0;
                } else {
                    linearParams.width = mPopupWeight * AllData.voice / 100;
                }
            } else {
                AllData.voice = 0;
                linearParams.width = 0;
            }
            tvCount.setText(AllData.voice + "");
            SendData.data = SendData.sendVoice(AllData.voice);
            SendData.needSend = true;
        }

        viewCount.setLayoutParams(linearParams);
    }

}
